import { Component, OnInit, ChangeDetectorRef, ViewChild, Inject, forwardRef } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { path } from '../../../../path.config';
import { masterService } from '../../../../../lib/master.service';
import { AppComponent } from '../../../../app.component';

@Component({
    selector: 'app-image-management-grid',
    templateUrl: './image-management-grid.component.html',
    styleUrls: ['./image-management-grid.component.css']
})
export class ImageManagementGridComponent implements OnInit {
    // api
    // 获取图片列表
    private getImgList = path.materialManagement.imageManagement.getImgList;

    // 列表项数组
    public rows: Array<any> = [];
    // 表格数据头部标题
    public columns: Array<any> = [
        { title: 'ID', name: 'id' },
        { title: '图片', name: 'imageUrl' },
        { title: '名称', name: 'imageName' },
        { title: '类型', name: 'extension' },
        { title: '大小', name: 'imageSize' },
        { title: '尺寸', name: 'resolution' },
        { title: '日期', name: 'createdTime' },
    ];
    // 当前页码
    public page: any = 1;
    // 一共多少页
    public itemsPerPage: number = 10;
    // 分页最多显示的页数
    public maxSize: number = 5;
    // 总页数计数变化时，事件数等于总页数计数
    public numPages: number = 1;
    // 总共的列表项数
    public totalItems: number = 0;
    // 分页器的文本配置
    public localText = {
        firstBtn: '首页',
        lastBtn: '末页',
        previousBtn: '上一页',
        nextBtn: '下一页'
    }

    public filter = {
        pageSize: this.itemsPerPage,
        pageIndex: this.page,
        imageName: ''
    }

    constructor(public _masterService: masterService,
        public cdRef: ChangeDetectorRef,
        @Inject(forwardRef(() => AppComponent)) private app: AppComponent) { }

    ngOnInit() {
        this.onChangeTable();
    }

    // 渲染表格
    public onChangeTable = (urlObj?, type?) => {

        if (type == 1 && urlObj) {
            this.filter.imageName = urlObj.imageName;
        } else if (urlObj) {
            this.filter.pageSize = urlObj.itemsPerPage;
            this.filter.pageIndex = urlObj.page;
        }

        this._masterService
            .getData(this.getImgList, this.filter)
            .subscribe((res) => {
                if (res.statusCode == 200) {
                    this.rows = res.data.items;
                    this.rows.forEach((row, i) => {
                        row.createTime = row.createTime * 1000;
                    })
                    this.totalItems = res.data.pagination.totalCount;
                    this.itemsPerPage = res.data.pagination.pageSize;
                    this.page = parseInt(res.data.pagination.pageIndex);
                    this.cdRef.detectChanges();
                } else if (res.statusCode == 401) {
                    this.app.logOff();
                } else {
                    this.app.toastError('错误信息：' + res.errorMessage);
                }
            })
    }
}
